/**
 * Created by 1 on 2016/12/31.
 */
(function(){
    function Keyboard(){
        this.keys={
            38: 'top',
            39: 'right',
            40: 'down',
            37: 'left'
        }
    }
    Keyboard.prototype={
        constructor:Keyboard,

        _init:function(board){
            this.board=board;
            var self=this;
            document.addEventListener("keydown",function(event){
                self.processKeyDown(event);
            })
        },
        processKeyDown:function(event){
            if(this.board.gameInst._state!=="playing"){
                return;
            }
            if(this.keys[event.keyCode]){
                this.press(this.keys[event.keyCode]);
            }
        },
        press:function(key){
            switch(key){
                case "top":this.board.shape.rotate();refresh=true;
                    break;
                case "down":if(this.board.validMove(0,1)){this.board.shape.y++;refresh=true;}
                    break;
                case "right":if(this.board.validMove(1,0)){this.board.shape.x++;refresh=true;}
                    break;
                case "left":if(this.board.validMove(-1,0)){this.board.shape.x--;refresh=true;}
                    break;
            }
            if(refresh){
                var self=this.board;
                self.refresh();
                self.shape.draw(self.context);
                if(key="down"){
                    window.clearInterval(window.Intervalid);
                    window.Intervalid=window.setInterval(function(){
                        self.tick();
                    },window.TetrisConfig.speed);
                }
            }

        }
    };
    window.Keyboard=Keyboard;
})();